﻿using System.IO;
using Budget.Config;
using Budget.Core.DomainModel;
using Budget.Data;
using NHibernate;
using NUnit.Framework;

namespace Budget.Tests.Infrastructure.Database
{
    [TestFixture]
    [Category("InMemoryDataBase")]
    public abstract class InmemoryDatabaseTestBase
    {
        private const string dbFileName = "test.db";

        protected ISession currentSession;

        private ITransaction currentTransaction;

        [TestFixtureSetUp]
        public void FixtureSetUp()
        {
            if (!File.Exists(dbFileName))
            {
                DB.Migrate("sqlite", BudgetConfig.InmemoryFileConnection);
            }

            DB.Init(new InMemoryConfig(BudgetConfig.InmemoryFileConnection));
        }

        [SetUp]
        public void SetUp()
        {
            currentSession = DB.Factory.OpenSession();
            currentTransaction = currentSession.Transaction;
            currentTransaction.Begin();
        }

        [TearDown]
        public void TearDown()
        {
            currentTransaction.Rollback();
            currentSession.Clear();
            currentSession.Dispose();
        }

        public int Count<T>() where T : BaseEntity
        {
            return currentSession.QueryOver<T>().RowCount();
        }
    }
}